Imports IWshRuntimeLibrary

Public Class frmMain
    Dim tabsViewed(3) As Boolean
    Dim dbTypes(2) As String

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'setup the dbtype array
        'to translate the selected DB type into the XML serverConfig value
        dbTypes(0) = "sql2000"
        dbTypes(1) = "sql2005"

        lblIntro.Text = lblIntro.Text & "Welcome to the installation of the ERN Server!"
        lblIntro.Text = lblIntro.Text & ControlChars.CrLf
        lblIntro.Text = lblIntro.Text & "- On the File Settings tab you will provide the directory you wish to install the ERN Server files.  There are only a few files that need to be installed and not much disk space is needed since most of the data is stored in the database."
        lblIntro.Text = lblIntro.Text & ControlChars.CrLf
        lblIntro.Text = lblIntro.Text & "- On the Database Settings tab, you will have to provide us with a user and password that has 'sa' type priviledges on your SQL Server 2000 server.  If needed, we will create a database specifically for ERN.  If tables already exist, you will have the choice of if you want us to drop them first before creating them (we suggest you do this to ensure the table structures are the same).  If you choose to drop the tables - PLEASE MAKE SURE YOU HAVE BACKUPS (if you want them).  NO BACKUPS ARE MADE OR DATA PRESERVATION WITH THIS INSTALL (which doesn't matter if this is your first install of ERN)."
        lblIntro.Text = lblIntro.Text & ControlChars.CrLf & ControlChars.CrLf
        'maybe remind user what ports ERN uses?
        lblIntro.Text = lblIntro.Text & ""

        txtLocation.Text = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) & "\ERN"
        txtServer.Text = Environment.GetEnvironmentVariable("computername")
        cmbServerType.SelectedIndex = 0
        txtUser.Text = "sa"
        txtDBName.Text = "ERN"
        tabsViewed(0) = True
        tabsViewed(1) = False
        tabsViewed(2) = False

        If IO.File.Exists(Application.StartupPath & "\license.txt") Then
            If frmLicense.ShowDialog() = Windows.Forms.DialogResult.Cancel Then
                MsgBox("You must accept the license agreement if you wish to use this program.  Please rerun this setup program if you decide to accept the agreement.")
                Application.Exit()
            End If
        End If
    End Sub

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        Application.Exit()
    End Sub

    Private Sub btnInstall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInstall.Click
        Dim doInstall As Boolean
        Dim wsh As New IWshRuntimeLibrary.WshShell
        Dim shortcut As IWshRuntimeLibrary.IWshShortcut
        Dim DB As System.Data.SqlClient.SqlConnection
        Dim cmd As New Data.SqlClient.SqlCommand
        Dim sqlFile As IO.StreamReader
        Dim line As String = ""
        Dim sql As String
        Dim xml As Xml.XmlTextWriter
        Dim uninstallFile As IO.TextWriter
        Dim unFiles() As String
        Dim unRegs() As String
        Dim unFile As Integer = 0
        Dim unReg As Integer = 0
        Dim i As Integer
        Dim fileCopyOK As Boolean = True

        Const fileCount As Integer = 3
        Const dirCount As Integer = 2
        Const regCount As Integer = 1
        Dim sqlCount As Integer = 2
        Const shortcutCount As Integer = 1
        Const configCount As Integer = 1

        ReDim unFiles(fileCount + shortcutCount)
        ReDim unRegs(regCount)

        btnInstall.Enabled = False
        btnExit.Enabled = False
        btnBrowse.Enabled = False
        btnTest.Enabled = False

        lblStatus.Text = "Performing checks..."

        'make sure they've viewed all three tabs before installing!
        If tabsViewed(1) And tabsViewed(1) = tabsViewed(2) Then
            doInstall = True
        Else
            If MsgBox("You have not reviewed the default options.  Are you sure you want to continue with the installation?", MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton1, "Confirmation to accept defaults") = MsgBoxResult.Yes Then
                doInstall = True
            Else
                doInstall = False
            End If
        End If

        If doInstall Then
            If txtLocation.Text = "" Then doInstall = False

            If txtServer.Text = "" Then doInstall = False
            If txtUser.Text = "" Then doInstall = False
            If txtDBName.Text = "" Then doInstall = False

            If chkDoSQL.Checked Then
                If chkDropTables.Checked Then
                    If MsgBox("You have chosen to drop any existing ERN tables before doing the installation.  This can result in data loss if ERN has been previously installed.  Are you sure you want to do this?", MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton1, "Confirmation to DROP tables") = MsgBoxResult.No Then
                        doInstall = False
                    End If
                End If
                lblStatus.Text = "Checking database connection..."
                If Not testConnection() Then
                    MsgBox("Error in database connection!")
                    doInstall = False
                End If
            End If
        End If

        If doInstall Then
            'calculate progress bar step
            If chkDropTables.Checked Then sqlCount = sqlCount + 1
            If chkDoSQL.Checked Then
                progress.Step = Math.Ceiling(100 / (configCount + dirCount + fileCount + regCount + shortcutCount + sqlCount + 1 + 1))
            Else
                progress.Step = Math.Ceiling(100 / (configCount + dirCount + fileCount + regCount + shortcutCount + 1 + 1))
            End If

            'create directories
            lblStatus.Text = "Creating directories..."
            IO.Directory.CreateDirectory(txtLocation.Text)
            progress.PerformStep()
            IO.Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) & "\ERN")
            progress.PerformStep()

            'install files
            lblStatus.Text = "Copying files..."
            Try
                IO.File.Copy(Application.StartupPath & "\ERN_server.exe", txtLocation.Text & "\ERN_server.exe", True)
            Catch
                fileCopyOK = False
            End Try
            unFiles(unFile) = txtLocation.Text & "\ERN_server.exe"
            unFile = unFile + 1
            progress.PerformStep()
            Try
                IO.File.Copy(Application.StartupPath & "\ErrorHandling.dll", txtLocation.Text & "\ErrorHandling.dll", True)
            Catch
                fileCopyOK = False
            End Try
            unFiles(unFile) = txtLocation.Text & "\ErrorHandling.dll"
            unFile = unFile + 1
            progress.PerformStep()
            Try
                IO.File.Copy(Application.StartupPath & "\euu.exe", txtLocation.Text & "\euu.exe", True)
            Catch
                fileCopyOK = False
            End Try
            progress.PerformStep()

            'modify registry
            lblStatus.Text = "Modifying the registry..."
            Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).SetValue("ERN Server", txtLocation.Text & "\ern_server.exe")
            unRegs(unReg) = "HKLM::SOFTWARE\Microsoft\Windows\CurrentVersion\Run::ERN Server"
            unReg = unReg + 1
            progress.PerformStep()

            'create DB
            If chkDoSQL.Checked Then
                lblStatus.Text = "Creating the database..."
                dbConnect(DB)
                'if not exists (select 1 from sys.databases where name = 'dan') create database dan
                cmd.Connection = DB

                'do a different test depending on sql server type - what a PIA
                If dbTypes(cmbServerType.SelectedIndex) = "sql2005" Then
                    cmd.CommandText = "if not exists (select 1 from sys.databases where name = '" & txtDBName.Text & "') create database " & txtDBName.Text
                ElseIf dbTypes(cmbServerType.SelectedIndex) = "sql2000" Then
                    cmd.CommandText = "if not exists (select 1 from master.dbo.sysdatabases where name = '" & txtDBName.Text & "') create database " & txtDBName.Text
                End If
                cmd.ExecuteNonQuery()
                cmd.CommandText = "use " & txtDBName.Text
                cmd.ExecuteNonQuery()
                progress.PerformStep()

                'run sql scripts
                lblStatus.Text = "Running SQL scripts..."
                If chkDropTables.Checked Then
                    'drop tables!
                    sqlFile = New IO.StreamReader(Application.StartupPath & "\drops.sql")
                    While Not sqlFile.EndOfStream
                        sql = ""
                        line = sqlFile.ReadLine
                        While line <> "GO" And Not sqlFile.EndOfStream
                            sql = sql & ControlChars.CrLf & line
                            line = sqlFile.ReadLine()
                        End While
                        If line <> "GO" Then sql = sql & ControlChars.CrLf & line
                        cmd.CommandText = sql
                        cmd.ExecuteNonQuery()
                    End While
                    sqlFile.Close()
                    sqlFile = Nothing
                    progress.PerformStep()
                End If
                'create tables
                sqlFile = New IO.StreamReader(Application.StartupPath & "\creates.sql")
                While Not sqlFile.EndOfStream
                    sql = ""
                    line = sqlFile.ReadLine
                    While line <> "GO" And Not sqlFile.EndOfStream
                        sql = sql & ControlChars.CrLf & line
                        line = sqlFile.ReadLine()
                    End While
                    If line <> "GO" Then sql = sql & ControlChars.CrLf & line
                    cmd.CommandText = sql
                    cmd.ExecuteNonQuery()
                End While
                progress.PerformStep()
            End If

            'create start menu shortcuts
            lblStatus.Text = "Creating shortcuts..."
            shortcut = CType(wsh.CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) & "\ERN\ERN Server.lnk"), IWshRuntimeLibrary.IWshShortcut)
            With shortcut
                .TargetPath = txtLocation.Text & "\ern_server.exe"
                .WorkingDirectory = txtLocation.Text
                .WindowStyle = 1
                .Description = "ERN Server"
                .IconLocation = .TargetPath
                .Save()
            End With
            unFiles(unFile) = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) & "\ERN\ERN Server.lnk"
            unFile = unFile + 1
            progress.PerformStep()

            'create XML config file
            xml = New Xml.XmlTextWriter(txtLocation.Text & "\serverConfig.xml", Nothing)

            With xml
                .Indentation = 4
                .IndentChar = " "
                .Formatting = .Indentation
                .WriteStartDocument()

                .WriteStartElement("General")
                .WriteElementString("dbServerName", txtServer.Text)
                .WriteElementString("dbUserName", txtUser.Text)
                .WriteElementString("dbPassword", txtPassword.Text)
                .WriteElementString("dbName", txtDBName.Text)
                .WriteElementString("dbType", dbTypes(cmbServerType.SelectedIndex))

                .WriteEndElement() 'end GENERAL

                .WriteEndDocument()
                .Flush()
                .Close()
            End With
            progress.PerformStep()

            'build uninstall info file
            uninstallFile = IO.File.CreateText(txtLocation.Text & "\uninstallServer.log")
            uninstallFile.WriteLine("files:" & unFiles.Length - 2)
            uninstallFile.WriteLine("registries:" & unRegs.Length - 1)
            For i = 0 To unFiles.Length - 1
                If unFiles(i) <> "" Then uninstallFile.WriteLine(unFiles(i))
            Next
            For i = 0 To unRegs.Length - 1
                If unRegs(i) <> "" Then uninstallFile.WriteLine(unRegs(i))
            Next
            uninstallFile.Close()
            progress.PerformStep()

            'create the add/remove programs info
            Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", True).CreateSubKey("ERN Server")
            Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ERN Server", True).SetValue("DisplayName", "ERN Server")
            Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ERN Server", True).SetValue("DisplayVersion", "")
            Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ERN Server", True).SetValue("HelpLink", "http://www.noworriescomputerhelp.com/ern")
            Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ERN Server", True).SetValue("NoModify", "1", Microsoft.Win32.RegistryValueKind.DWord)
            Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ERN Server", True).SetValue("NoRepair", "1", Microsoft.Win32.RegistryValueKind.DWord)
            Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ERN Server", True).SetValue("Publisher", "Dan Cleveland")
            Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ERN Server", True).SetValue("UninstallString", ControlChars.Quote & txtLocation.Text & "\euu.exe" & ControlChars.Quote & " uninstallServer.log")
            Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ERN Server", True).SetValue("URLInfoAbout", "http://www.noworriescomputerhelp.com/ern")
            Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ERN Server", True).SetValue("URLUpdateInfo", "http://www.noworriescomputerhelp.com/ern")
            Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ERN Server", True).SetValue("DisplayIcon", ControlChars.Quote & txtLocation.Text & "\ern_server.exe" & ControlChars.Quote)
            progress.PerformStep()

            If chkRunNow.Checked Then
                Dim procInfo As New Diagnostics.ProcessStartInfo
                With procInfo
                    .FileName = txtLocation.Text & "\ern_server.exe"
                    .WorkingDirectory = txtLocation.Text
                End With
                Process.Start(procInfo)
            End If

            If Not fileCopyOK Then MsgBox("Some destination files are in use and could not be copied", MsgBoxStyle.OkOnly, "ERN Server Setup")
            MsgBox("Installation complete!")
            Application.Exit()
        Else
            btnInstall.Enabled = True
            btnExit.Enabled = True
            btnBrowse.Enabled = True
            btnTest.Enabled = True
            MsgBox("Installation aborted")
        End If
    End Sub

    Private Sub tabSections_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabSections.SelectedIndexChanged
        tabsViewed(tabSections.SelectedIndex) = True
    End Sub

    Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
        dlgOpen.ShowDialog()

        If MsgBox("Create a new subdirectory '" & dlgOpen.SelectedPath & "\ERN'?", MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton1, "Confirmation to DROP tables") = MsgBoxResult.Yes Then
            txtLocation.Text = dlgOpen.SelectedPath & "\ERN"
        Else
            txtLocation.Text = dlgOpen.SelectedPath
        End If
    End Sub

    Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click
        If testConnection() Then
            MsgBox("Success!")
        Else
            MsgBox("Error in connection!")
        End If
    End Sub

    Private Function testConnection() As Boolean
        Dim DB As New System.Data.SqlClient.SqlConnection
        Dim connectStr As String
        Dim ok As Boolean = True

        'connectStr = "Initial Catalog=" & txtDBName.Text & ";"
        'connectStr = connectStr & "data source=" & txtServer.Text & ";"
        connectStr = "data source=" & txtServer.Text & ";"
        connectStr = connectStr & "min pool size=3;max pool size=50;"
        connectStr = connectStr & "user id= " & txtUser.Text & ";"
        connectStr = connectStr & "password = " & txtPassword.Text & ";"

        DB.ConnectionString = connectStr
        Try
            DB.Open()
        Catch
            ok = False
        End Try

        If ok Then
            DB.Close()
        End If

        Return ok
    End Function

    Private Function dbConnect(ByRef DB As System.Data.SqlClient.SqlConnection) As Boolean
        Dim connectStr As String
        Dim ok As Boolean = True

        connectStr = "data source=" & txtServer.Text & ";"
        connectStr = connectStr & "min pool size=3;max pool size=50;"
        connectStr = connectStr & "user id= " & txtUser.Text & ";"
        connectStr = connectStr & "password = " & txtPassword.Text & ";"

        DB = New System.Data.SqlClient.SqlConnection
        DB.ConnectionString = connectStr
        Try
            DB.Open()
        Catch
            ok = False
        End Try

        Return ok
    End Function

    Private Sub chkDoSQL_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkDoSQL.CheckedChanged
        Me.chkDropTables.Enabled = chkDoSQL.Checked
    End Sub
End Class
